package com.lvtn.adsonandroid;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class PublishedAdsActivity extends Activity {
    // declare variables
	private static String PublishedAdsURL = "http://10.0.2.2/android/GetPublishedAds.php";
	private static String HiddenAdsURL = "http://10.0.2.2/android/HiddenAds.php";
	private static String AppearenAdsURL = "http://10.0.2.2/android/AppearenAds.php";
	private ProgressDialog pDialog;
	private String email;
	private String news_id;
	public int position_1;
	JSONParser jParser = new JSONParser();
	ArrayList<Item> Data;
	JSONArray data_array = null;
	ListView list;
	ListAdapter adapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_published_ads);
		email = getIntent().getStringExtra(ManageActivity.EXTRA_MESSAGE);
		Data = new ArrayList<Item>();
		Log.d("asdasdasda","adasdada");
		list = (ListView) findViewById(R.id.listview);
		list.setLongClickable(true);
		list.setOnItemLongClickListener(new OnItemLongClickListener(){
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
				//Item item = Data.get(position);
			    position_1 = position;
				registerForContextMenu(findViewById(R.id.listview));
				return false;
				//return;
			}
		});
		list.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					 Item tem= Data.get(position);
					 Intent intent = new Intent(PublishedAdsActivity.this, DetailNewsActivity.class);
					 intent.putExtra("date", tem.getPubdate());
					 intent.putExtra("user_name", tem.getUser());
					 intent.putExtra("price", tem.getPrice());
					 intent.putExtra("title", tem.getTitle());
					 intent.putExtra("detail", tem.getDetail());
					 intent.putExtra("news_id", tem.getId());
					 intent.putExtra("user_email", tem.getEmail());
					 intent.putExtra("link", tem.getLink());
					 startActivity(intent);		

				}
			});		
		// Loading daftar rumah sakit in Background 
		//Thread
		Log.d("asdasdasda","adasdada");
		new GetAllNews().execute();
	}
//	@Override
	//public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
		//Item item = Data.get(position);
//		this.position = position;
//		registerForContextMenu(findViewById(R.id.listview));
//		return false;
		//return;
//	}
	@Override
	 public void onCreateContextMenu(ContextMenu menu, View v,
	 ContextMenuInfo menuInfo) {
	 // TODO Auto-generated method stub
	 super.onCreateContextMenu(menu, v, menuInfo);
	 getMenuInflater()
	 .inflate(R.menu.context_menu, menu);
	 }
	 @Override
	 public boolean onContextItemSelected(MenuItem item) {
	 switch(item.getItemId())
	 {
	 case R.id.look:
		 Item tem= Data.get(position_1);
		 Intent intent = new Intent(PublishedAdsActivity.this, DetailNewsActivity.class);
		 intent.putExtra("date", tem.getPubdate());
		 intent.putExtra("user_name", tem.getUser());
		 intent.putExtra("price", tem.getPrice());
		 intent.putExtra("title", tem.getTitle());
		 intent.putExtra("detail", tem.getDetail());
		 intent.putExtra("news_id", tem.getId());
		 intent.putExtra("user_email", tem.getEmail());
		 intent.putExtra("link", tem.getLink());
		 startActivity(intent);
		 break;
	 case R.id.hidden :
	     new Hidden_Ads().execute();
	      break;
	 case R.id.appearen :
		 new Appearen_Ads().execute();
		 break;
	 }
	 return super.onContextItemSelected(item);
	 }

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode,	data);
			// if result code 100
			if (resultCode == 100) {
				// if result code 100 is received
				// means user edited/deleted record
				// reload this screen again
				Intent intent = getIntent();
				finish();
				startActivity(intent);
			}
		}
class GetAllNews extends AsyncTask<String, String, String> {
		
		/**
		* Before starting background thread Show Progress Dialog
		* */
			@Override
			protected void onPreExecute() {
				Log.d("asdasdasda","adasdada");
				super.onPreExecute();
				pDialog = new ProgressDialog(PublishedAdsActivity.this);
				pDialog.setMessage("Loading...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(false);
				pDialog.show();
			}
		/**
		* getting All record data from url
		* */
			protected String doInBackground(String... args) {
		// Building Parameters
				Log.d("asdasdasda","adasdada");
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("tag", "get_published_ads"));
				params.add(new BasicNameValuePair("email", email));
		// getting JSON string from URL
				JSONObject json = jParser.makeHttpRequest(PublishedAdsURL, "GET", params);
		// Check your log cat for JSON reponse
				Log.d("getPublishedAds: ", json.toString());
				try {
		// Checking for SUCCESS TAG
					int success = json.getInt("success");
					if (success == 1) {
				// Ada record Data (SUCCESS = 1)
				// Getting Array of daftar_rs
						data_array = json.getJSONArray("news");
				// looping through All daftar_rs
						for (int i = 0; i < data_array.length(); i++) {
							JSONObject c = data_array.getJSONObject(i);
					// Storing each json item in variable
							String news_id = c.getString("id");
							String email = c.getString("user_email");
							String title = c.getString("title");
							String price = c.getString("price");
							String detail = c.getString("details");
							String link_image = c.getString("link_image");
							String date = c.getString("created_at");
							String user_name = c.getString("user_name");
							//Log.d("tenuserobj", user_name);
					// creating new HashMap
							Item objItem = new Item();
					// adding each child node to HashMap key => value
							objItem.setTitle(title);
							objItem.setPrice(price);
							objItem.setPubdate(date);
							objItem.setUser(user_name);
						//	Log.d("objsetUser",objItem.setUser(user_name));
							objItem.setLink(link_image);
							objItem.setDetail(detail);
							objItem.setId(news_id);
							objItem.setEmail(email);
					// adding HashList to ArrayList
							Data.add(objItem);
						}
					} else {
				// Tidak Ada Record Data (SUCCESS = 0)
				// Akan menutup aplikasi
			//	Toast toast = Toast.makeText(NewsActivity.this, "Không có tin nào cả", Toast.LENGTH_SHORT);
				//toast.show();
						return null;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			return null;
			}
		/**
		* After completing background task Dismiss the progress 
		dialog
		* **/
			protected void onPostExecute(String file_url) {
		
				if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
				}
				if(null == Data || Data.size() == 0){
					Toast toast = Toast.makeText(getApplicationContext(), "Không có tin nào cả", Toast.LENGTH_SHORT);
					toast.show();
				}
				else{
			// updating UI from Background Thread
					
					NewsRowAdapter objAdapter = new NewsRowAdapter(PublishedAdsActivity.this,R.layout.item_list, Data);
					list.setAdapter(objAdapter);
				}
			}
		}
class Hidden_Ads extends AsyncTask<String, String, Boolean> {
	
	/**
	* Before starting background thread Show Progress Dialog
	* */
		@Override
		protected void onPreExecute() {
			Log.d("asdasdasda","adasdada");
			super.onPreExecute();
			pDialog = new ProgressDialog(PublishedAdsActivity.this);
			pDialog.setMessage("Sending...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
	/**
	* getting All record data from url
	* */
		protected Boolean doInBackground(String... args) {
	// Building Parameters
			Log.d("asdasdasda","adasdada");
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("tag", "HiddenAds"));
			params.add(new BasicNameValuePair("news_id", news_id));
		//	params.add(new BasicNameValuePair("email_comuser", email_comuser));
		//	params.add(new BasicNameValuePair("comment", comment));
	// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(HiddenAdsURL, "POST", params);
	// Check your log cat for JSON reponse
			Log.d("HiddenAds: ", json.toString());
			try {
	// Checking for SUCCESS TAG
				int success = json.getInt("success");
				if (success == 1) {
			         return true;
					}
				 else {
			
					return false;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		return null;
		}
	/**
	* After completing background task Dismiss the progress 
	dialog
	* **/
		protected void onPostExecute(Boolean success) {
	
			if (success) {
				pDialog.dismiss();
				Toast toast = Toast.makeText(getApplicationContext(), "Đã ẩn tin", Toast.LENGTH_SHORT);
				toast.show();
				finish();
			}
			
			else{
		// updating UI from Background Thread
				pDialog.dismiss();
				Toast toast = Toast.makeText(getApplicationContext(), "Ẩn tin không thành công", Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}
class Appearen_Ads extends AsyncTask<String, String, Boolean> {
	
	/**
	* Before starting background thread Show Progress Dialog
	* */
		@Override
		protected void onPreExecute() {
			Log.d("asdasdasda","adasdada");
			super.onPreExecute();
			pDialog = new ProgressDialog(PublishedAdsActivity.this);
			pDialog.setMessage("Sending...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
	/**
	* getting All record data from url
	* */
		protected Boolean doInBackground(String... args) {
	// Building Parameters
			Log.d("asdasdasda","adasdada");
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("tag", "AppearenAds"));
			params.add(new BasicNameValuePair("news_id", news_id));
		//	params.add(new BasicNameValuePair("email_comuser", email_comuser));
		//	params.add(new BasicNameValuePair("comment", comment));
	// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(AppearenAdsURL, "POST", params);
	// Check your log cat for JSON reponse
			Log.d("AppearenAds: ", json.toString());
			try {
	// Checking for SUCCESS TAG
				int success = json.getInt("success");
				if (success == 1) {
			         return true;
					}
				 else {
			
					return false;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		return null;
		}
	/**
	* After completing background task Dismiss the progress 
	dialog
	* **/
		protected void onPostExecute(Boolean success) {
	
			if (success) {
				pDialog.dismiss();
				Toast toast = Toast.makeText(getApplicationContext(), "Đã hiện tin", Toast.LENGTH_SHORT);
				toast.show();
				finish();
			}
			
			else{
		// updating UI from Background Thread
				pDialog.dismiss();
				Toast toast = Toast.makeText(getApplicationContext(), "Hiện lại tin không thành công", Toast.LENGTH_SHORT);
				toast.show();
			}
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.published_ads, menu);
		return true;
	}
}
